﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace USArray
{
    public class BetterListNoGC<T> : BetterList<T> where T : unmanaged
    {
        ArrayNoGC<T> nogc;

        /// <summary>
        /// BetterList 的无GC版本，这两个参数都很重要
        /// </summary>
        /// <param name="capacity">初始数组容量</param>
        /// <param name="istemp">是用临时内存分配器，还是持久内存分配器。true =持久化分配器 </param>
        /// 临时分配器只能用一帧，除非这个Betterlist 只在一个函数内使用，否则肯定是不能这么干。
        /// 持久化分配器一定要Free，否则就内存泄漏了。Free= 调用 BetterListNoGC.Release() 函数

        public BetterListNoGC(int capacity, bool isPersist)
        {
            nogc = ArrayNoGC<T>.Create(capacity, !isPersist);
            buffer = nogc.ToBufferNoGC();
            nogc.ResetLength(capacity);
        }


        protected override void AllocateMore()
        {
            var newlen = (buffer != null) ? Math.Max(buffer.Length << 1, 4) : 4;
            var newnogc = ArrayNoGC<T>.Create(newlen, nogc.IsTemp);
            newnogc.ResetLength(newlen);
            var newList = newnogc.ToBufferNoGC();


            //T[] newList = (buffer != null) ? new T[Mathf.Max(buffer.Length << 1, 4)] : new T[4];
            if (buffer != null && size > 0) buffer.CopyTo(newList, 0);
            buffer = newList;

            nogc.Free();
            nogc = newnogc;
        }

        protected override void AllocateMore(int newlen)
        {
            //var newlen = (buffer != null) ? Mathf.Max(buffer.Length << 1, 4) : 4;
            var newnogc = ArrayNoGC<T>.Create(newlen, nogc.IsTemp);
            newnogc.ResetLength(newlen);
            var newList = newnogc.ToBufferNoGC();


            //T[] newList = (buffer != null) ? new T[Mathf.Max(buffer.Length << 1, 4)] : new T[4];
            if (buffer != null && size > 0) buffer.CopyTo(newList, 0);
            buffer = newList;

            nogc.Free();
            nogc = newnogc;
        }
        public override T[] ToArray()
        {

            if (size > 0)
            {
                if (size < buffer.Length)
                {
                    //截取一个Buf出来
                    nogc.ResetLength(size);
                    var buf = nogc.ToBufferNew();
                    nogc.ResetLength(nogc.MaxLength);

                    return buf;

                }
            }
           
            {
                return null;
            }

        }


        public override void Release()
        {
            size = 0;

            buffer = null;
            nogc.Free();
        }
    }
}
